<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends My_Controller 
{
	
	//construct
	public function __construct()
	{
		parent::__construct();
		$this->layout_view = 'admin';
		if(!$this->session->userdata('logged_in'))
			redirect('login/');
	}
	public function logout()
	{
		$this->session->sess_destroy();
		redirect('login/');	
	}
	//Index/Dashboard
	public function index()
	{
		
	}
	
	public function php_test(){
		echo phpinfo();
	}
	
	public function feedback(){
		$this->title = 'Feedbacks';	
		$this->load->model('M_feedback');
		$this->data['feedback'] = $this->M_feedback->getFeedbacks();
	}
	
	public function reply_feedback(){
		$this->title = 'Reply to feedback';
		$id = $this->uri->segment(3);
		$this->load->model('M_feedback');
		$this->data['v']= $this->M_feedback->getFeedback($id);
		
		if($this->data['v']->replied)
			$this->data['replied'] = 1;
		
		if($this->input->post('send'))
		{
			$this->form_validation->set_rules('response', 'Response', 'required');
			if ($this->form_validation->run() == FALSE)
			{
				
			}
			else
			{
				
				$to = $this->input->post('email');
				$subject ="Reply to your feedback";
				$message = $this->input->post('response');
				$this->sendEmail($to, $subject, $message, 'Jurosalon Feedback Response');
				
				$this->load->model('M_feedback');
				$this->M_feedback->setMessage($id);
				
				set_redirect('success', 'Replied to feedback successfully!', 'admin/reply_feedback/'.$this->uri->segment(3));
			}
		}
	}
	
	public function stylists()
	{
		$this->title = 'Stylists';
		$this->load->model('M_users');
		$this->data['stylists'] = $this->M_users->getUsers('stylist');
		
	}
	
	
	public function add_stylist()
	{
		$this->title = 'Add Stylist';
		if($this->input->post('add_stylist'))
		{
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');
			$this->form_validation->set_rules('firstname', 'Firstname', 'required');
			$this->form_validation->set_rules('lastname', 'Lastname', 'required');
			$this->form_validation->set_rules('contact', 'Contact', 'required|integer');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
			if ($this->form_validation->run() == FALSE)
			{
				
			}
			else
			{
				$this->load->model('M_users');
				$data = clean_post('add_stylist', $this->input->post());
				if($this->M_users->add_user($data))
				{
					set_redirect('success', 'Stylist added successfully!', 'admin/add_stylist');
				}
				else{
					set_redirect('error', 'Oops!, something happened please try again later.');
				}
			}
		}
			
	}
	
	
	public function edit_stylist()
	{
		$id = $this->uri->segment(3);
		
		$this->load->model('M_users');
		$this->data['user'] = $this->M_users->getUser($id);
		
		
		
		if($this->input->post('save'))
		{
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('firstname', 'Firstname', 'required');
			$this->form_validation->set_rules('lastname', 'Lastname', 'required');
			$this->form_validation->set_rules('contact', 'Contact', 'required|integer');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
			if ($this->form_validation->run() == FALSE)
			{
				// do nothing	
			}
			else 
			{
				$data = clean_post('save', $this->input->post());	
				if($this->M_users->updateUser($data, $id))
					set_redirect('success', 'User updated successfully', 'admin/edit_stylist/'.$id);
				else
					set_redirect('error', 'Oops! something went wrong, please try again later', 'admin/edit_stylist/'.$id);
			}

		}
		
		
	}
	
	public function admin_users()
	{
		$this->title = 'Admin users';	
		$this->load->model('M_users');
		$this->data['admin'] = $this->M_users->getUsers('admin');
	}
	
	public function add_admin()
	{
		$this->title = 'Add admin';	
		if($this->input->post('add_admin'))
		{
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');
			if ($this->form_validation->run() == FALSE)
			{
				// do nothing	
			}
			else 
			{
				$this->load->model('M_users');
				$data = clean_post('add_admin', $this->input->post());
				if($this->M_users->add_user($data))
				{
					set_redirect('success', 'Admin added successfully!', 'admin/add_admin');
				}
				else
				{
					set_redirect('error', 'Oops!, something happened please try again later.');
				}
			}
				
		}
	}
	
	public function customers()
	{
		$this->title = 'Customers';	
		$this->load->model('M_users');
		$this->data['customers'] = $this->M_users->getUsers('customer');
		
		
	}
	
	public function add_customer()
	{
		$this->title = 'Add customer';	
		if($this->input->post('add_customer'))
		{
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');
			$this->form_validation->set_rules('firstname', 'Firstname', 'required');
			$this->form_validation->set_rules('lastname', 'Lastname', 'required');
			$this->form_validation->set_rules('contact', 'Contact', 'required|integer');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
			if ($this->form_validation->run() == FALSE)
			{
				// do nothing	
			}
			else 
			{
				$this->load->model('M_users');
				$data = clean_post('add_customer', $this->input->post());
				if($this->M_users->add_user($data))
				{
					set_redirect('success', 'Customer added successfully!', 'admin/add_customer');
				}
				else
				{
					set_redirect('error', 'Oops!, something happened please try again later.');
				}
			}
				
		}
	}
	
	
	public function edit_customer()
	{
		$id = $this->uri->segment(3);
		
		$this->load->model('M_users');
		$this->data['user'] = $this->M_users->getUser($id);
		
		
		
		if($this->input->post('save'))
		{
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('firstname', 'Firstname', 'required');
			$this->form_validation->set_rules('lastname', 'Lastname', 'required');
			$this->form_validation->set_rules('contact', 'Contact', 'required|integer');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
			if ($this->form_validation->run() == FALSE)
			{
				// do nothing	
			}
			else 
			{
				$data = clean_post('save', $this->input->post());	
				if($this->M_users->updateUser($data, $id))
					set_redirect('success', 'Customer updated successfully', 'admin/edit_customer/'.$id);
				else
					set_redirect('error', 'Oops! something went wrong, please try again later', 'admin/customers/');
			}

		}
		
		
	}
	
	
	public function reset_pw()
	{
		$id = $this->uri->segment(3);
		$newpassword = $this->generatePassword(10);
		$this->load->model('M_users');
		$user = $this->M_users->getUser($id);
		$this->M_users->change_pass($newpassword, $id);
		
		$to = $user->email;
		$message = 'Your Password has been resetted by the administrator<br/><br/> Your new password is: <h1>'.$newpassword.'</h1>';
		$title = 'Password Reset';		
		
		$this->sendEmail($to, 'Password Reset', $message, 'Password Reset');
		
		set_redirect('success', 'Password has been resetted successfully', 'admin/edit_customer/'.$id);
		
		
	}
	
	public function delete()
	{
		$type = $this->uri->segment(3);	
		$id = $this->uri->segment(4);
		
		if($type == 'stylists')
		{
			$this->load->model('M_users');
			if($this->M_users->deleteUser($id))
				set_redirect('success', 'Stylist deleted successfully', 'admin/'.$type);
		}
		
		if($type == 'customers')
		{
			$this->load->model('M_users');
			if($this->M_users->deleteUser($id))
				set_redirect('success', 'Customer deleted successfully', 'admin/'.$type);
		}
		
		if($type == 'products')
		{
			$this->load->model('M_products');
			if($this->M_products->deleteProduct($id))
				set_redirect('success', 'Product deleted successfully', 'admin/'.$type);
		}
		
		if($type == 'time_table'){
			$this->load->model('M_bookings');
			if($this->M_bookings->deleteTime($id))
				set_redirect('success', 'Time deleted successfully', 'admin/'.$type);
		}
		
		if($type == 'booking_list'){
			$this->load->model('M_bookings');
			if($this->M_bookings->deleteBooking($id))
				set_redirect('success', 'Booking deleted successfully', 'admin/'.$type);
		}
		
		if($type == 'order'){
			$this->load->model('M_products');
			if($this->M_products->deleteOrders($id))
				set_redirect('success', 'Booking deleted successfully', 'admin/orders');
		}
	}
	
	
	//products
	
	public function products()
	{
		$this->title= 'Products';
		$this->load->model('M_products');
		$this->data['products'] = $this->M_products->getProducts();
	}
	
	public function add_product()
	{
		$this->title = 'Add product';
		
					$cfg['upload_path'] = './assets/images/products';
					$cfg['allowed_types'] = 'gif|jpg|png';
					$cfg['max_size']	= '2048';
					$cfg['max_width']  = '1024';
					$cfg['max_height']  = '768';
					$this->load->library('upload', $cfg);
		if($this->input->post('add_product'))
		{
			$this->form_validation->set_rules('name', 'Product Name', 'required');
			$this->form_validation->set_rules('description', 'Product Description', 'required');
			$this->form_validation->set_rules('quantity', 'Product Quantity', 'required|integer');
			$this->form_validation->set_rules('price', 'Price', 'required|decimal');
			
			if($this->form_validation->run() == TRUE)
			{
				$data['name'] = $this->input->post('name');
				$data['description'] = $this->input->post('description');
				$data['quantity'] = $this->input->post('quantity');
				$data['price'] = $this->input->post('price');
				if($_FILES['userfile']['error'] == 4)
				{
					echo 'No file selected';	
				}
				else{
					
					if ($this->upload->do_upload())
					{
						$upload_data = $this->upload->data();
						$data['image'] = 'assets/images/products/'.$upload_data['file_name'];
						
						$this->load->model('M_products');
						
						$this->M_products->addProduct($data) ? 
							set_redirect('success', 'Product added successfulyy!', 'admin/add_product') : set_redirect('error', 'Cannot add product, please try again later', 'admin/add_product');
						
					}
					else
					{
					
						
					}
				

				}

			}// form validation end
		}
	}
	
	public function edit_product()
	{
		$id = $this->uri->segment(3);
		
		$this->load->model('M_products');
		$this->data['product'] = $this->M_products->getProduct($id);
		$this->data['id'] = $id;
		$cfg['upload_path'] = './assets/images/products';
		$cfg['allowed_types'] = 'gif|jpg|png';
		$cfg['max_size']	= '2048';
		$cfg['max_width']  = '1024';
		$cfg['max_height']  = '768';
		$this->load->library('upload', $cfg);
		
		$this->form_validation->set_rules('name', 'Product Name', 'required');
		$this->form_validation->set_rules('description', 'Product Description', 'required');
		$this->form_validation->set_rules('quantity', 'Product Quantity', 'required|integer');
		$this->form_validation->set_rules('price', 'Price', 'required|decimal');
		
			if($this->form_validation->run() == TRUE)
			{
				$data['name'] = $this->input->post('name');
				$data['description'] = $this->input->post('description');
				$data['quantity'] = $this->input->post('quantity');
				$data['price'] = $this->input->post('price');
				if($_FILES['userfile']['error'] == 4)
				{
					$this->load->model('M_products');
					$this->M_products->updateProduct($data, $id) ? 
						set_redirect('success', 'Product edited successfulyy!', 'admin/edit_product/'.$id) : set_redirect('error', 'Cannot edit product, please try again later', 'admin/edit_product/'.$id);
				}
				else{
					
					if ($this->upload->do_upload())
					{
						$upload_data = $this->upload->data();
						$data['image'] = 'assets/images/products/'.$upload_data['file_name'];
						
						$this->load->model('M_products');
						
						$this->M_products->updateProduct($data, $id) ? 
							set_redirect('success', 'Product edited successfulyy!', 'admin/edit_product/'.$id) : set_redirect('error', 'Cannot edit product, please try again later', 'admin/edit_product/'.$id);
						
					}
					else
					{
					
						
					}
				

				}

			}// form validation end
		
		
	}
	
	
	/*BOOKING START*/
	
	public function stylist_availability()
	{
		$this->title = 'Stylist Availability';
		
		
	}
	
	public function time_table() 
	{
		$this->title = 'Time Table';	
		$this->load->model('M_bookings');
		$this->data['times'] = $this->M_bookings->getTimes();
	}
	
	public function add_time(){
		$this->title = 'Add Time';	
		if($this->input->post('add_time')){
			$this->form_validation->set_rules('aps_time_from', 'Time From', 'required');
			$this->form_validation->set_rules('aps_time_to', 'Time To', 'required');
			if($this->form_validation->run() == FALSE){
				echo 'false';
			}
			else {
				$this->load->model('M_bookings');
				$data = clean_post('add_time', $this->input->post());
				if($this->M_bookings->addTime($data))
					set_redirect('succes', 'Time Added Successfully!', 'admin/add_time');
				else
					set_redirect('error', 'Failed to add time to the time table, please try again later', 'admin/add_time');
			}
		}

	}
	
	public function edit_time(){
		$id = $this->uri->segment(3);
		$this->title = 'Edit Time';	
		$this->load->model('M_bookings');
		$this->data['time'] = $this->M_bookings->getTime($id);
		$this->data['time_id'] = $id;
		if($this->input->post('edit_time')){
			$this->form_validation->set_rules('aps_time_from', 'Time From', 'required');
			$this->form_validation->set_rules('aps_time_to', 'Time To', 'required');
			if($this->form_validation->run() == FALSE){
				
			}
			else {
				$this->load->model('M_bookings');
				$data = clean_post('edit_time', $this->input->post());
				if($this->M_bookings->updateTime($data, $id))
					set_redirect('succes', 'Time Edited Successfully!', 'admin/edit_time/'.$id);
				else
					set_redirect('error', 'Failed to edit time to the time table, please try again later', 'admin/edit_time/'.$id);
			}
		}

	}
	
	public function booking_list(){
		$this->title = 'Booking List';
		$this->load->model('M_bookings');
		$this->data['bookings'] = $this->M_bookings->getAllBookings();
	}
	
	public function view_booking(){
		$id = $this->uri->segment('3');
		if($id == '')
			set_redirect('error', 'Please select a booking to view', 'admin/booking_list');
		$this->title = 'View Booking';
		$this->load->model('M_bookings');
		$bdetails = $this->M_bookings->getBooking($id);
		$this->data['b'] = $bdetails;
		$this->data['bid'] = $id;
		if(empty($bdetails))
			set_redirect('error', 'Invalid booking, please select a booking to view', 'admin/booking_list');

		
		if($this->input->post('save')){
			$this->load->model('M_bookings');
			if($this->M_bookings->setStatus(clean_post('save', $this->input->post()), $id)){
				
				$booking_status = $this->input->post('status');
				
				$to = $bdetails->cemail;
				$schedule = date('D M d', strtotime($bdetails->adate)).' '.date('g:i A', strtotime($bdetails->aps_time_from)).'-'.date('g:i A', strtotime($bdetails->aps_time_to));
				$message = "Hi! <br/> your booking with schecdule <br/><br/> $schedule <br/><br/> has been updated by the admin <br/>";

				
				if($booking_status == 'Pending')
					$message .= "It has been set to pending, Please await our notifications anytime soon!";
				else if($booking_status == 'Confirmed')
					$message .= "Your booking has been confirmed, please be online during your specified schedule to chat with our stylist";
				else
					$message .= "We are sorry to inform you that it has been cancelled.";
				
				$this->sendEmail($to, 'Jurosalon Booking Service', $message, 'Jurosalon Booking Service');
				
				set_redirect('success', 'Booking updated successfully', 'admin/view_booking/'.$id);
			}
			else
				set_redirect('error', 'Booking action failed, please try again later!', 'admin/view_booking/'.$id);
				
			
		}
		
	}
	/*BOOKING END*/
	
	public function orders(){
		$this->title = 'Orders';	
		$this->load->model('M_products');
		$this->data['orders'] = $this->M_products->getOrders();
	}
	
	public function view_order(){
		$id = $this->uri->segment(3);
		$user_id = $this->uri->segment(4);
		
		$this->load->model('M_products');
		$this->load->model('M_users');
		
		$this->data['user'] = $this->M_users->getUser($user_id);
		$this->data['items'] = $this->M_products->getPurchasedItems($id, $user_id);
		$this->data['order_data'] = $this->M_products->getOrder($id, $user_id);
		$this->data['order_id'] = $id;
		
		if($this->input->post('save')){

			$this->load->model('M_products');
			
			$to = $this->input->post('email');
			$message = 'Your order with the following items has been '.$this->input->post('action').'<br/><br/>';
			$message .= $this->input->post('html_items');
			$this->sendEmail($to, "Jurosalon Order", $message, "Jurosalon Order");
			
			$this->M_products->setOrderStatus($this->input->post('order_id'), $this->input->post('action')) ?	
				set_redirect('success', 'Order status has been updated', 'admin/view_order/'.$id.'/'.$user_id) :
				set_redirect('error', 'Cannot update order status', 'admin/view_order/'.$id.'/'.$user_id);
		}
	}
	
	public function set_featured()
	{
		$id = $this->uri->segment(3);	
		
		$this->load->model('M_products');
		$this->M_products->setProductFeatured($id) ? 
			set_redirect('success', 'Product has been set to be featured on the frontpage', 'admin/products') :
			set_redirect('error', 'Cannot set the product to featured', 'admin/products');
	}
	
	public function unset_featured()
	{
		$id = $this->uri->segment(3);
		$this->load->model('M_products');
		$this->M_products->unsetFeatured($id) ?
			set_redirect('success', 'Product has been unset to be featured on the frontpage', 'admin/products') :
			set_redirect('success', 'Cannot unset the product from being featured', 'admin/products');
	}
	
	public function update_password(){
		$this->load->model('M_users');
		echo $this->M_users->change_pass('testing', 55);
	}
	
	function generatePassword($length = 8) {
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$count = mb_strlen($chars);
	
		for ($i = 0, $result = ''; $i < $length; $i++) {
			$index = rand(0, $count - 1);
			$result .= mb_substr($chars, $index, 1);
		}
	
		return $result;
	}	
	
	public function sendtext(){
		$this->title = 'Send Text Message';	
	}
	
	private function sendEmail($to, $subject, $msg, $title){

			
		$message = '<html><body>';
		$message .= $msg;
		$message .= '</body></html>';
					
		$from = "admin@jurosalon.com";
		$headers = 'From: '.$title.' <'.$from.'>' . "\r\n";
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
		mail($to,$subject,$message,$headers);	
	}
}
?>